package cn.jindong.mall.product.service.impl;

import cn.jindong.mall.product.service.CategoryBrandRelationService;
import cn.jindong.mall.product.vo.Catalog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jindong.common.utils.PageUtils;
import cn.jindong.common.utils.Query;

import cn.jindong.mall.product.dao.CategoryDao;
import cn.jindong.mall.product.entity.CategoryEntity;
import cn.jindong.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    /**
     * 级联更新所有关联的数据
     * @param category
     */
    //缓存双写模式的注解
    //@CachePut
    //缓存失效模式的注解
    //@CacheEvict(value = "category",key = "'getLevel1Categorys'")
    //同时进行多种缓存操作
    /*@Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })*/
    //指定删除某个分区下的所有数据
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)//加一个本地同步锁解决缓存击穿问题
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("get Level 1 Categories........");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间：" + (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    //需要缓存的数据我们都要指定放到哪个名字的缓存
    //代表当前方法的结果需要缓存，如果缓存有，则不执行方法，没有则执行方法
    //@Cacheable(value = {"category"},cacheNames = { }, key = "'levelCategorys'")
    @Cacheable(value = {"category"},cacheNames = { }, key = "#root.method.name")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return  getCatalogJsonFromDbWithRedissonlock();
    }


    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonlock() {
        // 1 锁的名字。锁的粒度
        RLock lock = redisson.getLock("CatalogJson-lock");
        //不指定过期时间，看门狗机制就会触发
        lock.lock();
        //最佳实战
        //虽然时间过期不会续期，可以节省续期操作的开销，只要根据业务运行时间设置好过期时间就可以了
        //lock.lock(30,TimeUnit.SECONDS);
        Map<String, List<Catalog2Vo>> dataFromDB;
        try {
            dataFromDB = getCatalogJsonFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }


    private Map<String, List<Catalog2Vo>> getCatelogJsonWithRedisLock() {
        // 自己唯一的键值
        String uuid = UUID.randomUUID().toString();
        // 1. 去redis中抢锁，原子性，假设设置过期时间30s
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        // 抢锁成功
        Map<String, List<Catalog2Vo>> data = null;
        if (result) {
            // 2. 执行业务
            try {
                // 拿到锁以后，应该再去缓存中确定一次是否存在数据(上一个释放锁的人可能把数据放入缓存了)
                // 方法中包含了这段逻辑
                data =  getCatalogJsonFromRedis();
            } finally {
                //使用Lua脚本删除锁，防止获取string的值时，因为网络传输问题发送删锁命令时，锁已过期，新锁生成，删掉新锁的问题
                //原理是lua脚本一次发送，判断成功直接删除，不会再经过一次网络传输
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                stringRedisTemplate.execute(new DefaultRedisScript<Integer>(script) {}, Arrays.asList("lock"), uuid);
                return data;
            }
        } else {
            //    休眠100ms。再去尝试，相当于自旋
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("获取分布锁失败");
            }
            return getCatelogJsonWithRedisLock();
        }
    }


    public Map<String, List<Catalog2Vo>> getCatalogJsonFromRedis() {
        // 1.从缓存中读取分类信息
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 2. 缓存中没有，查询数据库
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            // 3. 查询到的数据存放到缓存中，将对象转成 JSON 存储
            stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB));
            return catalogJsonFromDB;
        }
        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
    }

    /**
     * 实际访问数据库，拿到三级分类数据，封装成指定格式
     * 最终需要一个 Map<id, List<Catelog2VO>>，map里面的键是catelog1Id，也就是一级分类的id
     * @return
     */
    //@Cacheable(cacheNames = {ProductConstant.CacheName.PRODUCT_CATEGORY},key = "'catelogJson'")
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {
        System.out.println("实际查询MySQL数据库...");
        // 查出所有的菜单
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 所有一级菜单
        List<CategoryEntity> level1Categories = categoryEntities.stream().filter(item -> item.getParentCid() == 0).collect(Collectors.toList());

        Map<String, List<Catalog2Vo>> catelogMap = level1Categories.stream()
                // collectors.toMap 生成map
                .collect(Collectors.toMap(
                        // 一级分类的catId作为map的键
                        level1Category -> level1Category.getCatId().toString(),
                        // 一级分类的所有二级分类作为map的值
                        leve1Category -> {
                            // 先过滤出这个一级分类下的全部二级分类
                            List<Catalog2Vo> catelog2VOList = categoryEntities.stream().filter(category -> category.getParentCid().equals(leve1Category.getCatId()))
                                    // 再讲二级分类实体类 -> Catelog2VO
                                    .map(level2Category -> {
                                        // 设置属性
                                        Catalog2Vo catelog2VO = new Catalog2Vo();
                                        catelog2VO.setCatelog1Id(leve1Category.getCatId().toString());
                                        catelog2VO.setId(level2Category.getCatId().toString());
                                        catelog2VO.setName(level2Category.getName());
                                        // Catelog2VO中有个字段是Catelog3VO
                                        // 先过滤出这个二级分类下的所有分类
                                        List<Catalog2Vo.Catelog3VO> catelog3VOList = categoryEntities.stream().filter(category -> category.getParentCid().equals(level2Category.getCatId()))
                                                // 再把这些三级分类对象 -> catelog3VO
                                                .map(level3Category -> {
                                                    // 设置属性
                                                    Catalog2Vo.Catelog3VO catelog3VO = new Catalog2Vo.Catelog3VO();
                                                    catelog3VO.setCatelog2Id(level2Category.getCatId().toString());
                                                    catelog3VO.setId(level3Category.getCatId().toString());
                                                    catelog3VO.setName(level3Category.getName());
                                                    return catelog3VO;
                                                }).collect(Collectors.toList());
                                        // 填充给catelog2VO对应的字段
                                        catelog2VO.setCatelog3List(catelog3VOList);
                                        return catelog2VO;
                                    }).collect(Collectors.toList());
                            // 返回catelog2VOList，作为map<k,v>的值
                            return catelog2VOList;
                        }));
        return catelogMap;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all
                .stream()
                .filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                })
                .map(categoryEntity -> {
                    //1、找到子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{
                    //2、菜单的排序
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }

}